package com.group4.Servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.group4.DAO.UserDAO;
import com.group4.DB.User;
import com.group4.Utility.Mail;

public class ForgotPasswordServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5060456746634608280L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String email = request.getParameter("email");

		PrintWriter out = response.getWriter();
		JsonObject jsonObject = new JsonObject();
		UserDAO user = User.getUserWithEmail(email);

		if (user != null && user.getID() != -1) {

			String forgotPasswordUrl = "http://titan.cmpe.boun.edu.tr:8083/Signport/forgot?email=";
			forgotPasswordUrl += user.getEmail();
			forgotPasswordUrl += "&key=";
			forgotPasswordUrl += user.getActivationKey();

			Mail mail = new Mail(user.getEmail(), "Forgot Password",
					forgotPasswordUrl);
			mail.send();

			jsonObject.addProperty("success", "Mail is sent");
			out.print(jsonObject);
			out.flush();

		} else {

			jsonObject.addProperty("error", "There is no such email");
			out.print(jsonObject);
			out.flush();
		}
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String email = request.getParameter("email");

		PrintWriter out = response.getWriter();
		JsonObject jsonObject = new JsonObject();
		UserDAO user = User.getUserWithEmail(email);

		if (user != null && user.getID() != -1) {

			String forgotPasswordUrl = "http://titan.cmpe.boun.edu.tr:8083/Signport/forgot?email=";
			forgotPasswordUrl += user.getEmail();
			forgotPasswordUrl += "&key=";
			forgotPasswordUrl += user.getActivationKey();

			Mail mail = new Mail(user.getEmail(), "Forgot Password",
					forgotPasswordUrl);
			mail.send();

			jsonObject.addProperty("success", "Mail is sent");
			out.print(jsonObject);
			out.flush();

		} else {

			jsonObject.addProperty("error", "There is no such email");
			out.print(jsonObject);
			out.flush();
		}

	}
}
